<?php

namespace App\Http\Controllers\V1\Upload;

use App\Http\Requests\V1\ImportDataRequest;
use App\Events\V1\ImportExportEvent;
use App\Models\V1\NewStudent;
use App\Models\V1\ResultMajors;
use Illuminate\Http\Request;
use Jenssegers\Agent\Agent;
use Maatwebsite\Excel\Facades\Excel;
USE Log;
use Auth;

class MajorsResultUploadController extends BaseExcelUploadController
{
    /**
     * 导入志愿录取结果数据
     *
     * @param Request $request
     */
    public function importData(ImportDataRequest $request)
    {
        $response = [
            'rspStatus' => false,
            'rspMsg' => '志愿录取结果数据导入失败！',
        ];

        if ($request->method() === 'POST') {
            // 验证请求
            $this->validateImport($request);
            $filePath = $request->input('successFile');
            $arrival_code = $this->getArrivalCode();
            if (empty($arrival_code)) {
                $response['rspStatus'] = false;
                $response['rspMsg'] = '请先启动迎新换届';
                return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
            }
            Excel::load($filePath, function($reader) use ($arrival_code) {
                $reader->limitColumns(5);
                //忽略空的cells
                $reader->ignoreEmpty();
                $data = $reader->toArray();
                collect($data) -> flatMap(function($item) use ($arrival_code) {
                    $insert_data = [
                        'arrival_code' => $arrival_code,
                        'exam_code' => $item[0],
                        'count' => $item[1],
                        'detail' => $item[2],
                        'name' => $item[3],
                        'code' => $item[4],
                    ];
                    if (!empty($item[0]) && !empty($item[4])) {
                        ResultMajors::updateOrCreate(['exam_code'=>$item[0]],$insert_data);
                    }
                });
            });

            $response['rspStatus'] = true;
            $response['rspMsg'] = [
                'type' => 'import',
                'msg' => '成功导入['.$request->input('successFile').']文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $request->getClientIp(), time(), $response['rspMsg']));

            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
    }

    /**
     * 导出志愿录取结果数据文件
     *
     * @param Request $request
     */
    public function exportData(Request $request)
    {
        $clientIP = $request->getClientIp();

//        $header = ['迎新代码', '学生姓名', '考试号', '证件号', '招生目录（大类专业/方向）', '填报志愿数','志愿详情','录取专业名称','录取专业代码'];
        $header = [ '考试号', '填报志愿数','志愿详情','录取专业名称','录取专业代码'];
        $arrival_code = $this->getArrivalCode();
        if (empty($arrival_code)) {
            $response['rspStatus'] = false;
            $response['rspMsg'] = '请先启动迎新换届';
            return response()->json($response)->header('Content-Type', 'text/html;charset=utf-8');
        }
        $custodian = ResultMajors::where('arrival_code',$arrival_code)->select('exam_code', 'code','name','count','detail')->get();
        $cellDatas = [$header];
        foreach ($custodian as $item) {
            $cellData = [
                $item->exam_code,
                $item->count,
                $item->detail,
                $item->name,
                $item->code,
            ];
            array_push($cellDatas, $cellData);
        }

        Excel::create(iconv('UTF-8', 'GBK','志愿录取结果'), function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('majors', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });

            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[志愿录取结果]导出文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }


    /****
     * 下载模版
     * @param Request $request
     */
    public function downData(Request $request)
    {
        $clientIP = $request->getClientIp();

        $header = [ '考试号', '填报志愿数','志愿详情','录取专业名称','录取专业代码'];
        $cellDatas = [$header];
        $cellData1 = ['111190128',3,'英语，日语，俄语','日语','20192'];
        array_push($cellDatas, $cellData1);
        Excel::create('志愿录取结果数据导入模版', function ($excel) use ($cellDatas, $clientIP) {
            $excel->sheet('majors', function ($sheet) use ($cellDatas) {
                $sheet->rows($cellDatas);
            });
            $response['rspMsg'] = [
                'type' => 'export',
                'msg' => '成功下载[志愿录取结果]模版文件',
            ];
            event(new ImportExportEvent(Auth::user(), new Agent(), $clientIP, time(), $response['rspMsg']));
        })->export('xls');
    }

    /****
     * 根据考试号获取学生信息
     * @param $code
     * @return mixed
     */
    private function getNewStudentByCode($code)
    {
        $student = NewStudent::where('exam_code', $code)->first();
        return $student;
    }

}
